package com.sharemarking.wa.platform.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.common.entity.DriverAttachment;
import com.sharemarking.wa.common.entity.DriverVerify;
import com.sharemarking.wa.common.entity.Org;
import com.sharemarking.wa.platform.dto.driverVerify.DriverAttachmentDto;
import com.sharemarking.wa.platform.dto.driverVerify.DriverVerifyDto;
import com.sharemarking.wa.platform.dto.driverVerify.TransportOrgListDto;
import com.sharemarking.wa.platform.mapper.DriverAttachmentMapper;
import com.sharemarking.wa.platform.mapper.DriverVerifyMapper;
import com.sharemarking.wa.platform.mapper.OrgMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dxy
 */
@Service
public class DriverVerifyService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private DriverVerifyMapper driverVerifyMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private DriverAttachmentMapper driverAttachmentMapper;


    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> addOrEdit() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String name = request.getParameter("name");
        String orgId = request.getParameter("orgId");
        String verifyList = request.getParameter("verifyList");

        if (StringUtils.isEmpty(name)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("name"));
        }
        if (StringUtils.isEmpty(verifyList)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("verifyList"));
        }

        //校验证件json格式是否正确
        List<DriverAttachment> driverAttachmentList;
        try {
            driverAttachmentList = JSON.parseArray(verifyList, DriverAttachment.class);
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.isDataError("verifyList JSON格式错误"));
        }


        //验证orgId的合法性
        if (StringUtils.isEmpty(orgId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("orgId"));
        }
        try {
            Integer.valueOf(orgId);
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.isDataError("数据类型错误"));
        }
        Org org = orgMapper.selectById(orgId);
        if (org == null) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("orgId错误"));
        }

        //判断是否已经验证过
        QueryWrapper<DriverVerify> queryOne = new QueryWrapper<>();
        queryOne.eq("member_id", memberId);
        DriverVerify driverVerifyQuery = driverVerifyMapper.selectOne(queryOne);
        if (driverVerifyQuery != null && driverVerifyQuery.getExamState() == 1) {
            throw RequestException.create(ResponseParams.isDataError("该司机已认证成功，请勿重复提交"));
        }


        //提交司机认证
        DriverVerify driverVerify = new DriverVerify();
        driverVerify.setMemberId(memberId);
        driverVerify.setExamState(0);

        for (DriverAttachment driverAttachment : driverAttachmentList) {
            //type为-1 ，获取头像的链接
            if (driverAttachment.getType().equals(-1)) {
                driverVerify.setHeadImg(driverAttachment.getAttachment());
                break;
            }
        }

        driverVerify.setOrgId(Integer.valueOf(orgId));
        driverVerify.setName(name);
        if (driverVerifyQuery == null || driverVerifyQuery.getId() == null) {
            //如果找不到记录，插入
            driverVerify.setCreateDate(new Date());
            driverVerifyMapper.insert(driverVerify);
        } else {
            //更新数据
            driverVerify.setUpdateDate(new Date());
            driverVerify.setId(driverVerifyQuery.getId());
            driverVerifyMapper.updateById(driverVerify);
            //全删认证图片
            Map<String, Object> map = new HashMap<>(16);
            map.put("driver_verify_id", driverVerifyQuery.getId());
            driverAttachmentMapper.deleteByMap(map);
        }

        //插入司机证件图片
        for (DriverAttachment driverAttachment : driverAttachmentList) {
            if (!driverAttachment.getType().equals(-1)) {
                driverAttachment.setDriverVerifyId(driverVerify.getId());
                driverAttachment.setCreateDate(new Date());
                driverAttachmentMapper.insert(driverAttachment);
            }
        }
        return ResponseParams.ok(null);
    }


    public ResponseParams<?> getInfo() throws Exception {
        Integer memberId = ss.getCurrentUserId();

        DriverVerifyDto driverVerifyListDto = driverVerifyMapper.getDriverVerifyInfo(memberId);

        //如果没有信息直接返回
        if (driverVerifyListDto == null) {
            return ResponseParams.ok(null);
        }

        //获取证件信息
        QueryWrapper<DriverAttachment> queryTwo = new QueryWrapper<>();
        queryTwo.eq("driver_verify_id", driverVerifyListDto.getId());
        List<DriverAttachment> driverAttachment = driverAttachmentMapper.selectList(queryTwo);


        //将实体转为dto
        List<DriverAttachmentDto> driverAttachmentDtoList = new ArrayList<>();
        for (DriverAttachment dt : driverAttachment) {
            DriverAttachmentDto driverAttachmentDto = new DriverAttachmentDto();
            BeanUtils.copyProperties(dt, driverAttachmentDto);
            driverAttachmentDtoList.add(driverAttachmentDto);
        }


        driverVerifyListDto.setVerifyList(driverAttachmentDtoList);
        return ResponseParams.ok(driverVerifyListDto);
    }


    public ResponseParams<?> getOrgList() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String searchStr = request.getParameter("searchStr");

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));


        Map<String, Object> params = new HashMap<>();
        if(!StringUtils.isEmpty(searchStr)){
            params.put("searchStr", searchStr);
        }
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);

        List<TransportOrgListDto> list = driverVerifyMapper.getTransportOrgList(params);

        return ResponseParams.ok(new Page<>(list, pageIndex, pageSize, driverVerifyMapper.getTransportOrgListCount(params), list.size() == pageSize));
    }


    public ResponseParams<?> isOrgVerify() {
        Integer memberId = ss.getCurrentUserId();

        DriverVerify isDriverVerify = driverVerifyMapper.isDriverVerify(memberId);

        Map<String, Object> params = new HashMap<>();
        if (isDriverVerify == null){
            params.put("code", 3);
        }else {
            params.put("code", isDriverVerify.getExamState());
            if (isDriverVerify.getExamState()==2){
                params.put("rejectReason", isDriverVerify.getRejectReason());
            }
        }
        params.put("messageNumber",driverVerifyMapper.getMessageNumber(memberId));
        return ResponseParams.ok(params);
    }


}
